import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import { DialogQueue } from '@/utils/dialogQueue'
import { agencyAsync } from '@/appox/appox'
import { appoxEnums } from '@/appox/appox'

export const useConfigEditorStore = defineStore('configEditor', () => {
  // 状态
  const dialogQueue = new DialogQueue()
  const configInfoTable = ref(new Map())
  const searchKey = ref('')
  const selectedConfigId = ref(null)
  const isEditing = ref(false)
  const mainStatus = ref(null)
  const childStatus = ref(null)
  const config = ref('')
  const details = ref(null)

  // 状态筛选
  const filterDisabled = ref(true)
  const filterOK = ref(true)
  const filterError = ref(true)
  const filterWarning = ref(true)

  // 计算属性
  const filteredConfigList = computed(() => {
    const key = searchKey.value.toLowerCase()
    return Array.from(configInfoTable.value.values())
      .filter(info => {
        // 先检查搜索关键词
        const matchesSearch = info.id.toLowerCase().includes(key) ||
          info.name.toLowerCase().includes(key)
        if (!matchesSearch) return false

        // 再检查状态筛选
        const status = info.status?.[0]
        switch (status) {
          case 'Disabled':
            return filterDisabled.value
          case 'Enabled':
            return filterOK.value
          case 'EnabledWithError':
            return filterError.value
          case 'EnabledWithWarning':
            return filterWarning.value
          default:
            return true
        }
      })
      .sort((a, b) => a.name.localeCompare(b.name))
  })

  const canEdit = computed(() => {
    return !!selectedConfigId.value
  })

  const canSave = computed(() => isEditing.value)

  const canDisable = computed(() => {
    if (!mainStatus.value || isEditing.value || !disableSupported.value) return false
    return mainStatus.value[0] !== appoxEnums.ConfigStatus.Disabled
  })

  const canEnable = computed(() => {
    if (!mainStatus.value || isEditing.value || !enableSupported.value) return false
    return mainStatus.value[0] === appoxEnums.ConfigStatus.Disabled
  })

  // 添加支持状态
  const disableSupported = ref(false)
  const enableSupported = ref(false)

  // 监听filteredConfigList的变化
  watch(filteredConfigList, (newList) => {
    if (selectedConfigId.value) {
      const selectedItem = newList.find(item => item.id === selectedConfigId.value)
      if (!selectedItem) {
        // 如果选中项不在列表中，清空右侧显示
        selectedConfigId.value = null
        isEditing.value = false
        mainStatus.value = null
        childStatus.value = null
        config.value = ''
        details.value = null
      }
    }
  })

  // 动作
  async function initialize() {
    configInfoTable.value.clear()
    searchKey.value = ''
    selectedConfigId.value = null
    isEditing.value = false
    mainStatus.value = null
    childStatus.value = null
    config.value = ''
    details.value = null
    disableSupported.value = false
    enableSupported.value = false

    try {
      // 获取处理器类列表
      const processors = await agencyAsync.getProcessorClassTable()
      for (const [id, info] of Object.entries(processors)) {
        const status = await agencyAsync.getModuleConfigStatus(null, id)
        configInfoTable.value.set(id, {
          id,
          name: info.title,
          type: 'processor',
          status
        })
      }

      // 获取本地类列表
      const natives = await agencyAsync.getNativeClassTable()
      for (const [id, info] of Object.entries(natives)) {
        const status = await agencyAsync.getModuleConfigStatus(null, id)
        configInfoTable.value.set(id, {
          id,
          name: info.title,
          type: 'native',
          status
        })
      }

      // 获取设备类列表
      const devices = await agencyAsync.getDeviceClassTable()
      for (const [id, info] of Object.entries(devices)) {
        const status = await agencyAsync.getModuleConfigStatus(null, id)
        configInfoTable.value.set(id, {
          id,
          name: info.title,
          type: 'device',
          status
        })
      }
    } catch (error) {
      console.error('Failed to load config info table:', error)
    }
  }

  async function selectConfig(configId) {
    if (!configId) {
      clearConfigInfo()
      return
    }

    selectedConfigId.value = configId
    isEditing.value = false

    try {
      // 并行获取所有需要的数据
      const [main, child, cfg, det, disableSupportedResult, enableSupportedResult] = await Promise.all([
        agencyAsync.getModuleConfigStatus(null, configId),
        agencyAsync.getModuleChildConfigStatus(null, configId),
        agencyAsync.getModuleConfig(null, configId),
        agencyAsync.getModuleDetails(configId),
        agencyAsync.isDisableModuleSupported(configId),
        agencyAsync.isEnableModuleSupported(configId)
      ])
      mainStatus.value = main
      childStatus.value = child
      config.value = formatConfig(cfg)
      details.value = det
      disableSupported.value = disableSupportedResult
      enableSupported.value = enableSupportedResult
    } catch (error) {
      console.error('Failed to load config info:', error)
    }
  }

  function formatConfig(config) {
    if (!config) return ''
    
    // 检查是否为XML格式
    if (config.trim().startsWith('<')) {
      try {
        const parser = new DOMParser()
        const xmlDoc = parser.parseFromString(config, "text/xml")
        
        if (!xmlDoc.querySelector('parsererror')) {
          return formatXml(config)
        }
      } catch (e) {
        console.warn('XML解析失败:', e)
      }
    }
    
    return config
  }

  function formatXml(xml) {
    try {
      const parser = new DOMParser()
      const doc = parser.parseFromString(xml, "text/xml")
      
      if (doc.querySelector('parsererror')) {
        return xml
      }
      
      let declaration = ''
      if (xml.startsWith('<?xml')) {
        const endIndex = xml.indexOf('?>') + 2
        declaration = xml.substring(0, endIndex) + '\n'
      }
      
      function formatNode(node, indent) {
        const tab = '  '
        let result = ''
        
        if (node.nodeType === Node.ELEMENT_NODE) {
          result += indent + '<' + node.nodeName
          
          const attributes = Array.from(node.attributes)
          if (attributes.length > 0) {
            for (const attr of attributes) {
              result += '\n' + indent + tab + attr.name + '="' + attr.value + '"'
            }
            result += '\n' + indent
          }
          
          const childNodes = Array.from(node.childNodes)
          if (childNodes.length === 0) {
            result += '/>\n'
          } else {
            result += '>\n'
            
            for (const child of childNodes) {
              result += formatNode(child, indent + tab)
            }
            
            result += indent + '</' + node.nodeName + '>\n'
          }
        } else if (node.nodeType === Node.TEXT_NODE) {
          const text = node.textContent.trim()
          if (text) {
            result += indent + text + '\n'
          }
        } else if (node.nodeType === Node.COMMENT_NODE) {
          result += indent + '<!--' + node.textContent + '-->\n'
        }
        
        return result
      }
      
      return declaration + formatNode(doc.documentElement, '')
    } catch (e) {
      console.warn('XML格式化失败:', e)
      return xml
    }
  }

  async function saveConfig() {
    if (!selectedConfigId.value || !isEditing.value) return

    try {
      let configToSave = config.value
      // 移除所有回车和空格缩进
      configToSave = configToSave.replace(/\s+/g, ' ').trim()
      await agencyAsync.setModuleConfig(null, selectedConfigId.value, configToSave)
      isEditing.value = false
      await selectConfig(selectedConfigId.value)
    } catch (error) {
      console.error('Failed to save config:', error)
    }
  }

  async function disableConfig() {
    if (!selectedConfigId.value || !canDisable.value) return

    try {
      await agencyAsync.disableModule(null, selectedConfigId.value)
      await selectConfig(selectedConfigId.value)
    } catch (error) {
      console.error('Failed to disable config:', error)
    }
  }

  async function enableConfig() {
    if (!selectedConfigId.value || !canEnable.value) return

    try {
      await agencyAsync.enableModule(null, selectedConfigId.value)
      await selectConfig(selectedConfigId.value)
    } catch (error) {
      console.error('Failed to enable config:', error)
    }
  }

  function clearConfigInfo() {
    mainStatus.value = null
    childStatus.value = null
    config.value = ''
    details.value = null
    disableSupported.value = false
    enableSupported.value = false
  }

  function show() {
    return dialogQueue.show({
      onLoaded: () => initialize()
    })
  }

  function hide() {
    dialogQueue.hide()
  }

  return {
    // 状态
    isVisible: dialogQueue.isVisible,
    configInfoTable,
    searchKey,
    selectedConfigId,
    isEditing,
    mainStatus,
    childStatus,
    config,
    details,
    // 状态筛选
    filterDisabled,
    filterOK,
    filterError,
    filterWarning,
    // 支持状态
    disableSupported,
    enableSupported,
    // 计算属性
    filteredConfigList,
    canEdit,
    canSave,
    canDisable,
    canEnable,
    // 动作
    initialize,
    selectConfig,
    saveConfig,
    disableConfig,
    enableConfig,
    clearConfigInfo,
    show,
    hide,
    getQueueLength: dialogQueue.getQueueLength.bind(dialogQueue),
    clearQueue: dialogQueue.clearQueue.bind(dialogQueue)
  }
}) 